<template>
  <view class="assistant-role-page uu-bc">
    <!-- <keep-alive> -->
      <component
        :is="activeComponent"
        :key="currentTab"
        v-if="activeComponent"
      >
        <template #bottom>
          <role-tabbar
            :tabs="tabItems"
            :current="currentTab"
            role="assistant"
            :use-router="false"
            @change="handleTabChange"
          />
        </template>
      </component>
    <!-- </keep-alive> -->
  </view>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import type { Component } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import type { TabItem } from '@/components/role-tabbar/role-tabbar.vue'
import AssistantCity from './components/assistant-city.vue'
import AssistantStore from './components/assistant-store.vue'
import AssistantOrders from './components/assistant-orders.vue'
import AssistantProfile from './components/assistant-profile.vue'

interface TabDefinition extends TabItem {
  component: Component
}

const tabDefinitions: TabDefinition[] = [
  { key: 'city', text: '同城', icon: 'TC', path: '/pages/assistant-role/index?tab=city', component: AssistantCity },
  { key: 'store', text: '门店', icon: 'MD', path: '/pages/assistant-role/index?tab=store', component: AssistantStore },
  { key: 'orders', text: '订单', icon: 'DD', path: '/pages/assistant-role/index?tab=orders', component: AssistantOrders },
  { key: 'profile', text: '我的', icon: 'WD', path: '/pages/assistant-role/index?tab=profile', component: AssistantProfile }
]

const componentMap = tabDefinitions.reduce<Record<string, Component>>((acc, item) => {
  acc[item.key] = item.component
  return acc
}, {})

const tabItems = tabDefinitions.map<TabItem>(({ component, ...item }) => item)

const currentTab = ref<string>(tabDefinitions[0].key)

const activeComponent = computed<Component | null>(() => componentMap[currentTab.value] || null)

const handleTabChange = (item: TabItem) => {
  if (componentMap[item.key]) {
    currentTab.value = item.key
  }
}

onLoad((options) => {
  const initial = (options?.tab as string) || ''
  if (initial && componentMap[initial]) {
    currentTab.value = initial
  }
})
</script>

<style scoped lang="scss">
.assistant-role-page {
  min-height: 100vh;
  box-sizing: border-box;
  padding-bottom: calc(120rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}
</style>
